package cn.xinfei.xdecision.data.core.frame.executors;

import cn.xinfei.xdecision.common.model.datax.datainterface.v2.VarInterfaceInfo;
import cn.xinfei.xdecision.common.model.datax.enums.ExecutorEnum;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataException;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import cn.xinfei.xdecision.common.service.datax.datainterface.v2.VarInterfaceInfoService;
import cn.xinfei.xdecision.data.core.cache.VarInterfaceCache;
import cn.xinfei.xdecision.data.core.vo.VarInterfaceInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;


@Slf4j
@Service
public class HttpExecutorFactory extends AbstractExecutorFactory<Long, VarInterfaceInfoVO> {

    @Autowired
    VarInterfaceInfoService varInterfaceInfoService;

    @Autowired
    VarInterfaceCache varInterfaceCache;

    @Override
    public VarInterfaceInfoVO buildInput(Long dataSourceId) {
        Optional<Map<Integer, VarInterfaceInfo>> varInterfaceInfoCache = Optional.ofNullable(varInterfaceCache.loadVarInterfaceMetaData());
        VarInterfaceInfo varInterfaceInfo;
        if (varInterfaceInfoCache.isPresent()) {
            log.info("HttpExecutorFactory 查询缓存 VarInterfaceCache");
            varInterfaceInfo = varInterfaceInfoCache.get().values()
                    .stream()
                    .filter(item -> Long.valueOf(item.getId()).equals(dataSourceId))
                    .findFirst().orElseThrow(() -> new XDecisionDataException(
                            XDecisionDataExceptionType.DATA_NO_SUCH_INTERFACE_DATASOURCE_ERROR));
        } else {
            varInterfaceInfo = varInterfaceInfoService.selectInterfaceById(dataSourceId);
        }
        VarInterfaceInfoVO interfaceVo = new VarInterfaceInfoVO();
        BeanUtils.copyProperties(varInterfaceInfo, interfaceVo);
        return interfaceVo;
    }

    @Override
    public ExecutorEnum getExecutorEnums() {
        return ExecutorEnum.HTTP;
    }
}
